package vip.meet;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DBHelper {

    /**
     * 只有一个String字段
     * @param connection
     * @param sql
     * @return
     * @throws SQLException
     */
    public static List<String> getStringList(Connection connection,String sql) throws SQLException {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        ArrayList<String> results = new ArrayList<>();
        while (rs.next()){
            results.add(rs.getString(1));
        }
        return results;
    }

    public static boolean execute(Connection connection,String sql) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(sql);
        return ps.execute();
    }

    public static boolean updateAll(Connection connection,List<String> sqls) throws SQLException {
        connection.setAutoCommit(false);
        Statement statement = connection.createStatement();
        for(String sql : sqls){
            statement.addBatch(sql);
        }
        int[] ints = statement.executeBatch();
        connection.commit();
        System.out.println(Arrays.toString(ints));
        connection.close();
        return ints.length == sqls.size();
    }

    public static boolean executeDDL(String db, String sql) throws SQLException {
        Connection ddlConnection = DBConnectionFactory.getDDLConnection(db);
        Statement statement = ddlConnection.createStatement();
        return statement.execute(sql);
    }
}
